package com.tju.resource.server.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.tju.resource.model.SysRole;
import com.tju.resource.tool.result.Result;
import com.tju.resource.tool.result.ResultEnum;
import com.tju.resource.tool.result.ResultUtil;
import com.tju.resource.tool.tool.ChineseExceptionUtils;
import com.tju.resource.tool.tool.Constants;
import com.tju.resource.mapper.SysPermissionMapper;
import com.tju.resource.model.SysPermission;
import com.tju.resource.server.SysPermissionService;
import com.tju.resource.tool.tool.EmptyUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 权限管理业务
 *
 * @Author CLS
 * @Date 2021/12/31 14:19
 */
@Slf4j
@Service
public class SysPermissionServiceImpl implements SysPermissionService {
    @Autowired
    private SysPermissionMapper sysPermissionMapper;
    @Autowired
    private ChineseExceptionUtils zh_CH;

    /**
     * 查询所有菜单
     *
     * @param permission 菜单信息
     * @return
     */
    @Override
    public Result<Object> selectSysPermissionList(SysPermission permission) {
        SysRole role = sysPermissionMapper.selectUserName(permission.getUserName()); //查询角色

        List<SysPermission> SysPermissionList;
        if (role != null) {
            if (role.getName().equals("老板")) {  //判断是不是超级管理员
                SysPermissionList = sysPermissionMapper.selectSysPermissionList(permission);
            } else { //否者就更加用户名查询权限
                SysPermissionList = sysPermissionMapper.selectSysPermissionListByUserName(permission);
            }
        } else {
            return ResultUtil.success(ResultEnum.UNKONW_ERROR);
        }
        Long withNodeId = 0L;
        //跟节点数据
        List<SysPermission> followNode = new ArrayList<>();
        //循环拿到目录
        for (SysPermission per : SysPermissionList) {
            if (per.getParentId().equals(withNodeId)) {
                per.setChildrenName("目录");
                followNode.add(per); //添加根目录的子节点
            }
        }
        //循环目录
        for (SysPermission per : followNode) {
            //递归获取子节点数据
            List<SysPermission> childNode = Children(per.getId(), SysPermissionList);
            per.setChildren(childNode);
        }
        return ResultUtil.success(ResultEnum.SUCCESS, followNode);
    }

    /**
     * 递归设置栏目的子节点
     *
     * @param id   父节点id
     * @param list 节点列表
     * @return
     */
    private List<SysPermission> getChild(Long id, List<SysPermission> list) {
        //子节点数据
        List<SysPermission> childNode = new ArrayList<>();
        list.forEach(cn -> {
            //遍历所有节点把子节点添加到 childNode中
            if (cn.getParentId().equals(id)) {
                childNode.add(cn);

            }
        });
        //递归设置子节点下的其它节点
        childNode.forEach(cn -> {
            cn.setChildren(getChild(cn.getId(), list));
        });
        //如果节点下没有子节点，返回一个空List（递归退出）
        if (childNode.size() == 0) {
            return new ArrayList<>();
        }
        return childNode;
    }

    /**
     * 递归设置栏目的子节点
     *
     * @param id   父节点id
     * @param list 节点列表
     * @return
     */
    private List<SysPermission> Children(Long id, List<SysPermission> list) {
        //子节点数据
        List<SysPermission> childNode = new ArrayList<>();
        list.forEach(cn -> {
            //遍历所有节点把子节点添加到 childNode中
            if (cn.getParentId().equals(id)) {
                childNode.add(cn);

            }
        });
        //递归设置子节点下的其它节点
        childNode.forEach(cn -> {
            if (cn.getType() == 1) {
                cn.setChildrenName("菜单");
            } else {
                cn.setChildrenName("按钮");
            }
            cn.setChildren(Children(cn.getId(), list));
        });
        //如果节点下没有子节点，返回一个空List（递归退出）
        if (childNode.size() == 0) {
            return new ArrayList<>();
        }
        return childNode;
    }


    /**
     * 查询是否存在子级
     *
     * @param parentId 菜单父级id
     * @return
     */
    @Override
    public int selectCountPermissionByParentId(Long parentId) {
        return sysPermissionMapper.selectCountPermissionByParentId(parentId);

    }

    /**
     * 查询菜单使用数量
     *
     * @param permissionId 菜单ID
     * @return 结果
     */
    @Override
    public int selectCountRolePermissionByPermissionId(Long permissionId) {
        return sysPermissionMapper.selectCountRolePermissionByPermissionId(permissionId);
    }

    /**
     * 删除菜单管理信息
     *
     * @param parentId 菜单ID
     * @return 结果
     */
    @Override
    @Transactional
    public Result<Object> deletePermissionByParentId(Long parentId) {
        try {
            if (EmptyUtils.isNotEmpty(parentId)) {
                if (sysPermissionMapper.deletePermissionByParentId(parentId) > 0) {
                    return ResultUtil.success(ResultEnum.SUCCESS, zh_CH.SuccessfullyDeleted);
                }
            }else {
                ResultUtil.error(ResultEnum.UNKONW_ERROR, zh_CH.MissingParameters);
            }
        } catch (Exception e) {
            log.error(e.getMessage());
        }
        return ResultUtil.error(ResultEnum.UNKONW_ERROR, zh_CH.FailedToDelete);

    }

    /**
     * 根据菜单ID查询信息
     *
     * @param parentId 菜单ID
     * @return 菜单信息
     */
    @Override
    public SysPermission SysPermissionByParentId(Long parentId) {
        return sysPermissionMapper.SysPermissionByParentId(parentId);
    }

    /**
     * 校验菜单名称是否唯一
     *
     * @param permission 菜单信息
     * @return 结果
     */
    @Override
    public String checkPermissionNameUnique(SysPermission permission) {
        Long id = permission.getId() == null ? -1L : permission.getId();
        SysPermission info = sysPermissionMapper.checkPermissionNameUnique(permission.getName());
        if (info != null && info.getId().longValue() != id.longValue()) {
            return Constants.MENU_NAME_NOT_UNIQUE;
        }
        return Constants.MENU_NAME_UNIQUE;
    }

    /**
     * 添加菜单
     *
     * @param permission 菜单信息
     * @return
     */
    @Override
    @Transactional
    public Result<Object> insertPermission(SysPermission permission) {
        try {
            SysPermission sysPermission = sysPermissionMapper.selectById(permission.getParentId());
            if (sysPermission != null) {
                if (sysPermission.getType() == 2) {
                    return ResultUtil.error(ResultEnum.UNKONW_ERROR, "按钮下面不能新增");
                }
            }
            permission.setCreateDate(new Date());
            if (sysPermissionMapper.insert(permission) > 0) {
                return ResultUtil.success(ResultEnum.SUCCESS, zh_CH.AddedSuccessfully);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ResultUtil.error(ResultEnum.UNKONW_ERROR, zh_CH.AddFailed);
    }

    /**
     * 修改菜单
     *
     * @param permission 菜单信息
     * @return
     */
    @Transactional
    @Override
    public Result<Object> updatePermission(SysPermission permission) {
        if (permission.getType() == 2) {
            QueryWrapper<SysPermission> query = new QueryWrapper<SysPermission>();
            query.eq("parent_id", permission.getId());
            if (sysPermissionMapper.selectList(query).size() != 0) {
                return ResultUtil.error(ResultEnum.UNKONW_ERROR, "不能修改为按钮下面有菜单或按钮");
            }
        }
        permission.setUpdateDate(new Date());
        if (sysPermissionMapper.updateById(permission) > 0) {
            return ResultUtil.success(ResultEnum.SUCCESS, zh_CH.SuccessfullyModified);
        }

        return ResultUtil.error(ResultEnum.UNKONW_ERROR, zh_CH.FailToEdit);
    }

    @Override
    public Result<Object> getMenusByUserName(String ugc) {
        Long withNodeId = 0L;
        //跟节点数据
        List<SysPermission> followNode = new ArrayList<>();
        try {
            //查询所有数据
            List<SysPermission> list = sysPermissionMapper.getMenusByUserName(ugc);
            if (list.size() <= 0) {
                throw new Exception(zh_CH.UserException);
            }
            list.forEach(menu -> {
                //添加根节点数据
                if (menu.getParentId().equals(withNodeId)) {
                    followNode.add(menu);
                }
            });
            //为跟节点数据添子节点数据
            followNode.forEach(fn -> {
                //递归获取子节点数据
                List<SysPermission> childNode = getChild(fn.getId(), list);
                //给根节点设置子节点
                fn.setChildren(childNode);
            });
            return ResultUtil.success(ResultEnum.SUCCESS, followNode);
        } catch (Exception e) {
            return ResultUtil.error(ResultEnum.UNKONW_ERROR, e.getMessage());
        }

    }


}
